from fastapi import APIRouter, Request, HTTPException
from app.services.shopify_oauth import exchange_access_token, save_access_token

router = APIRouter()

@router.get("/shopify/oauth/callback")
async def shopify_oauth_callback(request: Request):
    params = dict(request.query_params)
    code = params.get("code")
    shop = params.get("shop")
    state = params.get("state")
    hmac = params.get("hmac")
    # 这里建议校验 hmac 和 state，确保安全（略）

    if not code or not shop:
        raise HTTPException(status_code=400, detail="Missing code or shop")

    # 获取 access_token
    token_data = exchange_access_token(shop, code)
    access_token = token_data.get("access_token")
    if not access_token:
        raise HTTPException(status_code=400, detail="Failed to get access_token")

    # 保存到数据库
    save_access_token(shop, access_token)
    return {"msg": "OAuth success", "shop": shop}